package server

import (
	"context"
	"errors"
	__ "house-src/basic/proto"
	"house-src/handler/models"
	"house-src/untils"
	"strconv"
)

// 添加清洁师
func (s *Server) AddCleaner(_ context.Context, in *__.AddCleanerReq) (*__.AddCleanerResp, error) {
	var err error

	var cleaner models.Cleaner
	cleaner = models.Cleaner{
		CustomerId: int(in.CustomerId),
		RealName:   in.RealName,
		Desc:       in.Desc,
		Address:    in.Address,
		ClassType:  in.ClassType,
		Status:     1, //接单模式
	}
	if err = cleaner.AddCleaner(); err != nil {
		return nil, errors.New("添加失败")
	}

	return &__.AddCleanerResp{
		CleanerId: int64(cleaner.ID),
	}, nil
}

// 清洁师认证
func (s *Server) AuthCleaner(_ context.Context, in *__.AuthCleanerReq) (*__.AuthCleanerResp, error) {
	var err error

	var cleaner models.Cleaner
	if err = cleaner.GetCleanerById(int(in.CleanerId)); err != nil {
		return nil, errors.New("清洁师查询失败")
	}

	if cleaner.ID == 0 {
		return nil, errors.New("该清洁师不存在")
	}
	cleaner.ID = uint(in.CleanerId)
	cleaner.Image = in.Image
	if err = cleaner.AuthCleaner(int(in.CleanerId)); err != nil {
		return nil, errors.New("上传认证失败")
	}

	return &__.AuthCleanerResp{
		CleanerId: int64(cleaner.ID),
	}, nil
}

// 审核
func (s *Server) UpdateCheckStatus(_ context.Context, in *__.UpdateCheckStatusReq) (*__.UpdateCheckStatusResp, error) {
	var err error

	var cleaner models.Cleaner
	if err = cleaner.GetCleanerById(int(in.CleanerId)); err != nil {
		return nil, errors.New("清洁师查询失败")
	}

	if cleaner.ID == 0 {
		return nil, errors.New("该清洁师不存在")
	}

	var customer models.Customer
	if err = customer.GetCustomerById(cleaner.CustomerId); err != nil {
		return nil, errors.New("用户查询失败")
	}

	if customer.UType != 1 {
		return nil, errors.New("没有权限")
	}

	cleaner.ID = uint(in.CleanerId)
	cleaner.CheckStatus = int(in.Check)
	if err = cleaner.UpdateCheckStatus(int(in.CleanerId)); err != nil {
		return nil, errors.New("审核失败")
	}

	return &__.UpdateCheckStatusResp{
		CleanerId: int64(cleaner.ID),
	}, nil
}

// 清洁师列表
func (s *Server) GetCleanerList(_ context.Context, in *__.GetCleanerListReq) (*__.GetCleanerListResp, error) {

	var cleaner models.Cleaner
	list, _ := cleaner.GetCleanerList(in.ClassType)

	var cleanerList []*__.GetCleanerInfo
	for _, c := range list {
		cleanerList = append(cleanerList, &__.GetCleanerInfo{
			CleanerId:  int64(c.ID),
			CustomerId: int64(c.CustomerId),
			RealName:   c.RealName,
			Desc:       c.Desc,
			Address:    c.Address,
			ClassType:  c.ClassType,
			Image:      c.Image,
		})
	}

	//同步es
	var es untils.ES
	es.Index = "houses"
	for _, info := range cleanerList {
		es.Id = strconv.FormatInt(info.CleanerId, 10)
		es.Body = info
	}

	return &__.GetCleanerListResp{
		CleanerList: cleanerList,
	}, nil
}
